﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using static LiMinCRMPlugin.InterfaceDocking.TransportationModel;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 应收单删除插件
    /// </summary>
    /// <remarks>
    /// 功能：应收单在删除时自动传到CRM。
    /// 创建人：mey
    /// 创建日期：2024.3.26
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("应收单删除同步至CRM")]
    [HotUpdate]
    public class ReceivableDeleteToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            //编码
            e.FieldKeys.Add("FBillNo");
            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //立账类型
            e.FieldKeys.Add("FSetAccountType");
            //转销
            e.FieldKeys.Add("FIsWriteOff");

            //创建人
            e.FieldKeys.Add("FCreatorId");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);

            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string FSetAccountType = Convert.ToString(entity["FSetAccountType"]);//立账类型                 
                bool FIsWriteOff = Convert.ToBoolean(entity["IsWriteOff"]);//转销              
                if (FSetAccountType == "3" && FIsWriteOff == true)//只有转销的财务应收才删除
                {

                    DataTable dt = APISetting();
                    string httpUrl = dt.Rows[0]["F_RDLV_URL"].ToString();
                    string httpSystemId = dt.Rows[0]["F_RDLV_SystemId"].ToString();
                    string httpPassword = dt.Rows[0]["F_RDLV_Password"].ToString();

                    string UserAccount = "";//用户账号
                    DynamicObject User = entity["CreatorId"] as DynamicObject;//用户
                    if (User != null)
                    {
                        UserAccount = Convert.ToString(User["UserAccount"]);
                    }


                    string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                    string FID = Convert.ToString(entity["Id"]);//内码                      
                    string Number = entity["BillNo"].ToString();//编码

                    String currentTimeTamp = getTimestamp();
                    String md5Source = httpSystemId + httpPassword + currentTimeTamp;
                    String md5OfStr = Md5(md5Source).ToLower();


                    #region 查询赋值
                    ReceivableSelectModel.mainTable mainTable2 = new ReceivableSelectModel.mainTable()
                    {
                        djnm = FID,
                    };
                    //操作人员信息
                    ReceivableSelectModel.operationinfo operationinfo2 = new ReceivableSelectModel.operationinfo()
                    {
                        operatorAbAb = UserAccount,

                    };
                    ReceivableSelectModel.Header header2 = new ReceivableSelectModel.Header()
                    {
                        systemid = httpSystemId,
                        currentDateTime = currentTimeTamp,
                        Md5 = md5OfStr
                    };
                    ReceivableSelectModel.DataHeader dataHeader1 = new ReceivableSelectModel.DataHeader()
                    {
                        operationinfo = operationinfo2,
                        mainTable = mainTable2,
                        header = header2
                    };

                    var jsonS = JsonConvert.SerializeObject(dataHeader1);
                    jsonS = jsonS.ToString().Replace("operatorAbAb", "operator");
                    #endregion

                    #region 删除赋值
                    ReceivableDeleteModel.mainTable mainTable3 = new ReceivableDeleteModel.mainTable()
                    {
                        djnm = FID,
                    };
                    //操作人员信息
                    ReceivableDeleteModel.operationinfo operationinfo3 = new ReceivableDeleteModel.operationinfo()
                    {
                        operatorAbAb = UserAccount,

                    };
                    ReceivableDeleteModel.Header header3 = new ReceivableDeleteModel.Header()
                    {
                        systemid = httpSystemId,
                        currentDateTime = currentTimeTamp,
                        Md5 = md5OfStr
                    };
                    ReceivableDeleteModel.DataHeader dataHeader2 = new ReceivableDeleteModel.DataHeader()
                    {
                        operationinfo = operationinfo3,
                        mainTable = mainTable3,
                        header = header3
                    };

                    var jsonD = JsonConvert.SerializeObject(dataHeader2);
                    jsonD = jsonD.ToString().Replace("operatorAbAb", "operator");
                    #endregion


                    //查询是否存在
                    var httpJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/getDataByPK/select_bill", jsonS);

                    var arrresult = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(httpJson);//转换
                    var MainTable = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(arrresult["result"].ToString());//转换


                    if (MainTable.Count >= 1)//
                    {

                        var AddJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/deleteModeDataByPK/delete_bill", jsonD);

                        var Addresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(AddJson);//转换


                        if (Addresult.status == "1")
                        {
                            #region 应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = Number;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "应收单";
                            interfaceLog.FInvokeType = "应收单删除";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = jsonD.ToString();
                            interfaceLog.FReturnData = AddJson.ToString();
                            interfaceLog.FRequest = jsonD.ToString();
                            interfaceLog.FReturn = AddJson.ToString();
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }

                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            IOperationResult operationResult = new OperationResult();

                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = true,
                                Message = string.Format("CRM应收单数据删除成功！"),
                                MessageType = MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);

                            #endregion
                        }
                        else
                        {
                            #region 应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = Number;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "应收单";
                            interfaceLog.FInvokeType = "应收单删除";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = jsonD.ToString();
                            interfaceLog.FReturnData = AddJson.ToString();
                            interfaceLog.FRequest = jsonD.ToString();
                            interfaceLog.FReturn = AddJson.ToString();
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }

                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                            throw new KDException("删除失败", "CRM应收单数据删除失败，请重新删除！");


                            #endregion

                        }



                    }


                }
            }
        }
        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting()
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface");
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];

        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


    }
}
